package com.fivefu.core.config;

import com.fivefu.core.context.DynamicDataSourceContextHolder;
import com.fivefu.core.pojo.FfDataSource;
import com.fivefu.core.util.DataSourceUtil;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * @Author zhf
 * @Description
 * @Date 2021/3/3
 */
public class FFDynamicDS  extends AbstractRoutingDataSource {

    private Map<Object,Object> backupTargetDataSources;

    public  FFDynamicDS(DataSource defaultDataSource,Map<Object,Object> targetDataSOurce){
         backupTargetDataSources = targetDataSOurce;
         super.setDefaultTargetDataSource(defaultDataSource);
         super.setTargetDataSources(backupTargetDataSources);
         super.afterPropertiesSet();
    }
    // 添加多个数据源
    public void addDataSource(List<FfDataSource> ffDataSources){
        for(FfDataSource item : ffDataSources){
            this.backupTargetDataSources
                    .put(item.getKeyName(), DataSourceUtil.makeNewDataSource(item));
        }

        //覆盖原来的多数据源
        super.setTargetDataSources(backupTargetDataSources);
        //这个相当于数据源的设置
        //AbstractRoutingDataSource  是实现了 InitializingBean
        //AbstractRoutingDataSource  实例化之后回调用afterPropertiesSet
        //通过这个方法 我们覆盖掉的多数据源才会配置
        super.afterPropertiesSet();
    }
    //决定当前数据源的锁 -- 我们用数据源的key
    @Override
    protected  Object determineCurrentLookupKey()
    {
        return DynamicDataSourceContextHolder.getContextKey();
    }


}
